package com.cmw.socket.l_2_3;

import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;


public class Client {

    public static void main(String[] args) throws Exception{
        Socket socket = new Socket();
        //超时时间 3秒
        socket.setSoTimeout(3000);
        //本地连接端口：2000， 超时：3秒
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), 2000), 3000);
        System.out.println("已发起服务器连接，并进入后续流程...");
        System.out.println("客户端信息："+socket.getLocalAddress()+", 客户端端口号："+socket.getLocalPort());
        System.out.println("服务器端信息："+socket.getInetAddress()+", 客户端端口号："+socket.getPort());
        try{
            todo(socket);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        socket.close();
    }

    private static void todo(@NotNull Socket client) throws Exception{
        //构建键盘输入流
        InputStream in = System.in;
        BufferedReader input = new BufferedReader(new InputStreamReader(in));

        //得到Socket 输出流，并转换为打印流
        OutputStream outputStream = client.getOutputStream();
        PrintStream socketPrintStream = new PrintStream(outputStream);

        //得到Socket输入流并转换为 BufferedReader
        InputStream inputStream = client.getInputStream();
        BufferedReader socketBufferdReader = new BufferedReader(new InputStreamReader(inputStream));

        boolean flag = true;
        do {
            //键盘读一行
            String str = input.readLine();
            //发送到服务器
            socketPrintStream.println(str);
            //从服务器读取一行
            String echo = socketBufferdReader.readLine();
            if (null != echo && echo.equals("bye")) {
                flag = false;
            }else{
                System.out.println(echo);
            }
        }while (flag);

        input.close();
        socketPrintStream.close();
        socketBufferdReader.close();
        System.out.println("客户端已退出...");
    }
}
